<template>
  <pro-layout
    v-if="show"
    class="base-layout"
    :menus="menus"
    :collapsed="collapsed"
    :mediaQuery="query"
    :isMobile="isMobile"
    :handleMediaQuery="handleMediaQuery"
    :handleCollapse="handleCollapse"
    v-bind="settings"
  >
    <template v-slot:menuHeaderRender>
      <div class="logo-title" v-cloak>
        <img class="img" v-show="collapsed" src="@/assets/logo.png" />
        <div class="title" v-show="!collapsed">{{ title }}</div>
      </div>
    </template>

    <!-- 1.0.0+ 版本 pro-layout 提供 API,
          增加 Header 左侧内容区自定义
    -->
    <!-- <template v-slot:headerContentRender>
      <div>
        <a-tooltip title="刷新页面">
          <a-icon type="reload" style="font-size: 18px;cursor: pointer;" @click="() => { $message.info('只是一个DEMO') }" />
        </a-tooltip>
      </div>
    </template> -->
<!--    <template v-slot:headerContentRender v-if="!isMobile">-->
<!--      <MainMenu @reload="reload"/>-->
<!--    </template>-->

    <template v-slot:rightContentRender>
      <right-content :top-menu="settings.layout === 'topmenu'" :is-mobile="isMobile" :theme="settings.theme" />
    </template>

    <!--  顶部导航标签  -->
    <NavTags/>

    <!-- custom footer / 自定义Footer -->
    <template v-slot:footerRender>
      <div class="main-footer">版权所有 ©中海油能源发展有限公司采油服务分公司</div>
    </template>

    <!-- //:key="$route.fullPath" -->
    <div class="layout-container">
      <keep-alive :key="$route.fullPath" :include="keepAliveArr">
        <router-view v-if="isRouterAlive"/>
      </keep-alive>
    </div>
  </pro-layout>
</template>

<script>
import { SettingDrawer, updateTheme } from '@ant-design-vue/pro-layout'
import { CONTENT_WIDTH_TYPE, SIDEBAR_TYPE, TOGGLE_MOBILE_TYPE } from '@/store/mutation-types'

import defaultSettings from '@/config/defaultSettings'
import RightContent from '@/components/GlobalHeader/RightContent'

import { mapGetters, mapState } from 'vuex'
import NavTags from './components/NavTags';

export default {
  name: 'BasicLayout',
  components: {
    NavTags,
    SettingDrawer,
    RightContent,
  },
  provide() {
    return {
      reload: this.reload,
    }
  },
  data() {
    return {
      isRouterAlive: true,
      show: true,
      current: 'one',
      // preview.pro.antdv.com only use.
      isProPreviewSite: process.env.VUE_APP_PREVIEW === 'true' && process.env.NODE_ENV !== 'development',
      // end
      // isDev: process.env.NODE_ENV === 'development' || process.env.VUE_APP_PREVIEW === 'true',
      isDev: false,
      // base
      menus: [],
      // 侧栏收起状态
      collapsed: false,
      title: defaultSettings.title,
      settings: {
        // 布局类型
        layout: defaultSettings.layout, // 'sidemenu', 'topmenu'
        // CONTENT_WIDTH_TYPE
        contentWidth: defaultSettings.layout === 'sidemenu' ? CONTENT_WIDTH_TYPE.Fluid : defaultSettings.contentWidth,
        // 主题 'dark' | 'light'
        theme: defaultSettings.navTheme,
        // 主色调
        primaryColor: defaultSettings.primaryColor,
        fixedHeader: defaultSettings.fixedHeader,
        fixSiderbar: defaultSettings.fixSiderbar,
        colorWeak: defaultSettings.colorWeak,

        hideHintAlert: false,
        hideCopyButton: false,
        siderWidth: defaultSettings.siderWidth,
      },
      // 媒体查询
      query: {},

      // 是否手机模式
      isMobile: false,
    }
  },
  computed: {
    ...mapState({
      // 动态主路由
      mainMenu: (state) => state.permission.addRouters,
    }),
    ...mapGetters(['btnPermission', 'userInfo', 'keepAliveArr']),
  },
  created() {
    const routes = this.mainMenu.find((item) => item.path === '/')
    this.menus = (routes && routes.children) || []
    // 处理侧栏收起状态
    this.$watch('collapsed', () => {
      this.$store.commit(SIDEBAR_TYPE, this.collapsed)
    })
    this.$watch('isMobile', () => {
      this.$store.commit(TOGGLE_MOBILE_TYPE, this.isMobile)
    })
  },
  mounted() {
    const userAgent = navigator.userAgent
    if (userAgent.indexOf('Edge') > -1) {
      this.$nextTick(() => {
        this.collapsed = !this.collapsed
        setTimeout(() => {
          this.collapsed = !this.collapsed
        }, 16)
      })
    }

    // first update color
    // TIPS: THEME COLOR HANDLER!! PLEASE CHECK THAT!!
    if (process.env.NODE_ENV !== 'production' || process.env.VUE_APP_PREVIEW === 'true') {
      // updateTheme(this.settings.primaryColor)
    }

    //获取路由点击方法\跳转页面 ant-menu
    this.$nextTick(() => {
      var that = this
      //事件委托
      var node = document.getElementsByClassName('ant-menu-submenu-open')
      document.getElementsByClassName('ant-layout-sider-children')[0].addEventListener('click', function (e) {
        // console.log(e.target.ariaExpanded) //如果为true 则代表展开
        // console.log(e.target.innerText) //点击菜单的名称
        /** 二级菜单 */
        if (e.target.ariaExpanded || node.length > 1) {
          switch (e.target.innerText) {
            case '厂坞修管理':
              that.$router.push({ path: '/maintenance/PlantDockRepairHome' })
              break
            case '新厂坞修管理':
              that.$router.push({ path: '/maintenanceNew/PlantDockRepairNewHome' })
              break
          }
        }
        var titleNode = document.getElementsByClassName('ant-menu-submenu-title')[0]
        // console.log(node,'titleNode');
        /**一级菜单 */
        if (e.target.localName == 'span') {
          var href = window.location.hash
          // console.log( href,' href');
          switch (e.target.innerText) {
            case '台账管理':
              //判断当前页面是否是 首页
              if (href != '#/standing/standingBookHome' && that.permissionEach('standingHome')) {
                // console.log(titleNode)
                // e.preventDefault()
                // e.stopPropagation()
                // e.stopImmediatePropagation()
                // return false
                that.$router.push('/standing/standingBookHome')
              }
              break
            case '合规性管理':
              //判断当前页面是否是 首页
              if (href != '#/regulations/regulationsHome' && that.permissionEach('regulationsHome')) {
                that.$router.push('/regulations/regulationsHome')
              }
              break
            case '项目管理':
              //判断当前页面是否是 首页
              if (href != '#/projectManagement/projectManagementHome' && that.permissionEach('projectManagementHome')) {
                that.$router.push('/projectManagement/projectManagementHome')
              }
              break
            case '风险和隐患管理':
              //判断当前页面是否是 首页
              if (href != '#/risk/riskHome' && that.permissionEach('riskHome')) {
                that.$router.push('/risk/riskHome')
              }
              break
            case '新维修管理':
              //判断当前页面是否是 首页
              if (href != '#/maintenanceNew/maintenanceNewHome' && that.permissionEach('maintenanceNewHome')) {
                that.$router.push('/maintenanceNew/maintenanceNewHome')
              }
              break

            case '维修管理':
              //判断当前页面是否是 首页
              if (href != '#/maintenance/maintenanceHome' && that.permissionEach('maintenanceHome')) {
                that.$router.push('/maintenance/maintenanceHome')
              }
              break
            //判断当前页面是否是 首页
            case '软管管理':
              if (href != '#/flexible/flexibleHome' && that.permissionEach('flexibleHome')) {
                that.$router.push('/flexible/flexibleHome')
              }
              break
            //判断当前页面是否是 首页
            case '资产管理':
              if (href != '#/property/propertyHome' && that.permissionEach('propertyHome')) {
                that.$router.push('/property/propertyHome')
              }
              break
            //判断当前页面是否是 首页
            case '变更管理':
              if (href != '#/alteration/alterationHome' && that.permissionEach('alterationHome')) {
                that.$router.push('/alteration/alterationHome')
              }
              break
            //判断当前页面是否是 首页
            case '动态和应急资源管理':
              if (
                href != '#/emergencyResources/emergencyResourcesHome' &&
                that.permissionEach('emergencyResourcesHome')
              ) {
                that.$router.push('/emergencyResources/emergencyResourcesHome')
              }
              break
            //判断当前页面是否是 首页
            case '关键绩效指标':
              if (href != '#/keyIndicator/keyIndicatorHome' && that.permissionEach('keyIndicatorHome')) {
                that.$router.push('/keyIndicator/keyIndicatorHome')
              }
              break
            //判断当前页面是否是 首页
            case '报表管理':
              if (href != '#/statement/statementHome' && that.permissionEach('statementHome')) {
                that.$router.push('/statement/statementHome')
              }
              break
            //判断当前页面是否是 首页
            case '完整性审核':
              if (href != '#/integrity/IntegrityHome' && that.permissionEach('integrityHome')) {
                that.$router.push('/integrity/IntegrityHome')
              }
              break
            //判断当前页面是否是 首页
            case '检验检测':
              if (href != '#/inspection/inspectionHome' && that.permissionEach('inspectionHome')) {
                that.$router.push('/inspection/inspectionHome')
              }
              break
            //判断当前页面是否是 首页
            case '人员管理':
              if (href != '#/personnel/personnelHome' && that.permissionEach('personnelHome')) {
                that.$router.push('/personnel/personnelHome')
              }
              break
          }
        }
      })
    })
  },
  watch: {
    $route() {
      // var siderWidth = this.$route.path == '/largeScreen' ? 0 : defaultSettings.siderWidth;
      // this.settings.siderWidth = siderWidth;
    },
    mainMenu() {
      const routes = this.mainMenu.find((item) => item.path === '/')
      this.menus = (routes && routes.children) || []
    },
  },
  methods: {
    permissionEach(path) {
      for (var i = 0; i < this.userInfo.menuList.length; i++) {
        if (path == this.userInfo.menuList[i].path) {
          return true
        }
      }
    },
    handleClick(e) {
      this.current = e.key
      this.$router.push({
        path: this.current,
      })
    },
    handleMediaQuery(val) {
      this.query = val
      if (this.isMobile && !val['screen-xs']) {
        this.isMobile = false
        return
      }
      if (!this.isMobile && val['screen-xs']) {
        this.isMobile = true
        this.collapsed = false
        this.settings.contentWidth = CONTENT_WIDTH_TYPE.Fluid
        // this.settings.fixSiderbar = false
      }
    },
    handleCollapse(val) {
      this.collapsed = val
    },
    handleSettingChange({ type, value }) {
      console.log('type', type, value)
      type && (this.settings[type] = value)
      switch (type) {
        case 'contentWidth':
          this.settings[type] = value
          break
        case 'layout':
          if (value === 'sidemenu') {
            this.settings.contentWidth = CONTENT_WIDTH_TYPE.Fluid
          } else {
            this.settings.fixSiderbar = false
            this.settings.contentWidth = CONTENT_WIDTH_TYPE.Fixed
          }
          break
      }
    },
    reload() {
      this.isRouterAlive = false
      this.$nextTick(function () {
        this.isRouterAlive = true
      })
    },
  },
}
</script>

<style lang="less">
@import './BasicLayout.less';

.layout-container {
  padding: 0 16px;
}

.main-footer {
  text-align: center;
  background: var(--layout-background);
  color: var(--nav-tag-font-color);
}
</style>